import { getProtocolWsUrl } from "./ws";

class VoiceSocket {
  speechSocket: WebSocket | null = null;
  offline_text: string = "";
  rec_text: string = "";
  constructor() {
    this.speechSocket = null;
  }
  public handleWithTimestamp(tmptext: any, tmptime: any) {
    if (tmptime == null || tmptime === "undefined" || tmptext.length <= 0) {
      return tmptext;
    }
    tmptext = tmptext.replace(/。/g, ","); // in case there are a lot of "。"
    let words = tmptext.split(",");
    let jsontime = JSON.parse(tmptime); //JSON.parse(tmptime.replace(/\]\]\[\[/g, "],[")); // in case there are a lot segments by VAD
    let char_index = 0;
    let text_withtime = "";
    for (let i = 0; i < words.length; i++) {
      if (words[i] === "undefined" || words[i].length <= 0) {
        continue;
      }
      text_withtime =
        text_withtime + jsontime[char_index][0] / 1000 + ":" + words[i] + "\n";
      char_index = char_index + words[i].length;
    }
    return text_withtime;
  }
  public getJsonMessage(jsonMsg: any) {
    console.log("message: " + JSON.parse(jsonMsg.data)["text"]);
    let rectxt = "" + JSON.parse(jsonMsg.data)["text"];
    let asrmodel = JSON.parse(jsonMsg.data)["mode"];
    let is_final = JSON.parse(jsonMsg.data)["is_final"];
    let timestamp = JSON.parse(jsonMsg.data)["timestamp"];
    if (asrmodel === "2pass-offline" || asrmodel === "offline") {
      this.offline_text =
        this.offline_text + this.handleWithTimestamp(rectxt, timestamp);
      this.rec_text = this.offline_text;
    } else {
      this.rec_text = this.rec_text + rectxt;
    }
    if (is_final) {
      this.close();
    }
    return this.rec_text;
  }
  public start() {
    return new Promise((reslove, reject) => {
      this.speechSocket = new WebSocket(
        getProtocolWsUrl(
          `${window.location.host}/cnpc-web/supgpt-app/chat-tool-voice-ident/`
        )
      );
      // this.speechSocket = new WebSocket(
      //   `ws://123/tpt-mobile-web/supgpt-app/chat-tool-voice-ident/`
      // );
      this.speechSocket.onopen = () => {
        reslove(this.speechSocket);
        const chunk_size = [5, 10, 5];
        const language = "zh-CN";

        const request = {
          chunk_size: chunk_size,
          wav_name: "h5",
          is_speaking: true,
          chunk_interval: 10,
          mode: "2pass",
          language: language,
        };
        if (this.speechSocket) this.speechSocket.send(JSON.stringify(request));
      };
      this.speechSocket.onerror = (err) => {
        reject(err);
      };
    });
  }
  public send(data: any) {
    if (!this.speechSocket) return;
    if (this.speechSocket.readyState === 1) {
      this.speechSocket.send(data);
    }
  }
  public close() {
    if (!this.speechSocket) return;
    this.speechSocket.close();
  }
}

export default VoiceSocket;
